package com.example.lib_cache.network.exception;

import android.content.Context;
import android.util.Log;
import com.example.lib_common.dao.MyPublicInterface;
import com.google.gson.JsonParseException;

import org.json.JSONException;

import io.github.prototypez.appjoint.AppJoint;
import io.reactivex.functions.Consumer;

/**
 * 通用异常回调的Consumer
 */
public abstract class ErrorConsumer implements Consumer<Throwable> {

    protected Context context;

    public final static String TAG = ErrorConsumer.class.getSimpleName();

    public ErrorConsumer(Context context){
        this.context = context;
    }

    public ErrorConsumer(){}

    @Override
    public void accept(Throwable throwable)throws Exception{
        ApiException ex;

        if(throwable instanceof ApiException){
            ex = (ApiException) throwable;
        }else {
            ex = ApiException.handleException(throwable);
        }
        Log.d("ErrorConsumer","得到code" + ex.getCode());
        if(ex.getCode().equals("503")){
            Log.d("ErrorConsumer","响应登录" + ex.getCode());
            toLogin();
        }
        error(ex);
    }

    private void toLogin(){
        MyPublicInterface myPublicInterface = AppJoint.service(MyPublicInterface.class);
        myPublicInterface.toLogin(context);
    }

    protected abstract void error(ApiException ex);
}
